<template>
  <div class="panel">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return

  chart = echarts.init(chartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}：危险度 {c}%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 100,
      axisLine: {
        lineStyle: {
          color: '#33ffd0'
        }
      },
      axisLabel: {
        color: '#33ffd0',
        formatter: '{value}%'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(51, 255, 208, 0.1)'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: ['褐斑病', '玉米锈病', '玉米黑粉病', '霜霉病', '灰叶斑病', '叶枯病'],
      axisLine: {
        lineStyle: {
          color: '#33ffd0'
        }
      },
      axisLabel: {
        color: '#33ffd0'
      }
    },
    series: [
      {
        type: 'bar',
        data: [
          {
            value: 85,
            itemStyle: {
              color: '#F56C6C'
            }
          },
          {
            value: 65,
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            value: 45,
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            value: 35,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            value: 28,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            value: 15,
            itemStyle: {
              color: '#67C23A'
            }
          }
        ],
        barWidth: '40%',
        label: {
          show: true,
          position: 'right',
          color: '#ffffff',
          formatter: '{c}%'
        }
      }
    ]
  }

  chart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
